package file;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

import org.junit.Test;

public class RandomAccessFileTest {
	
	@Test
	public void write() throws IOException{
		
		RandomAccessFile file = new RandomAccessFile("a.txt", "rw");
		
		String data = "asdfwrqewrq\r\nasdfasdfasdfsa";
		file.writeInt(data.length());
		System.out.println(data.length() + "---------");
		file.writeChar('\n');
		file.write(data.getBytes());
		file.writeChar('\n');
		
		data = "123412342314\n23412341324";
		file.writeInt(data.length());
		System.out.println(data.length() + "---------");
		file.writeChar('\n');
		file.write(data.getBytes());
		file.writeChar('\n');
		file.close();
	}

	public static void main(String[] args) throws FileNotFoundException, IOException {
		try(RandomAccessFile file = new RandomAccessFile("D:/edgeServer/out.edge", "rw")){
			
			file.writeUTF("asdfasdf");
			file.writeUTF("22134");
			file.writeUTF("edf23");
			file.writeUTF("sdf12");
			
			file.seek(0);
			
			System.out.println("data:" + read(file) + ",positon:" + getPositionFlag(file));
		}
	}
	
	public static String read(RandomAccessFile file) throws IOException{
		String data = file.readUTF();
		setPositionFlag(file, file.getFilePointer());
		return data;
	}
	
	public static void setPositionFlag(RandomAccessFile file, long position) throws IOException{
		long originPos = file.getFilePointer();
		file.seek(0);
		file.writeLong(position);
		file.seek(originPos);
	}
	
	public static long getPositionFlag(RandomAccessFile file) throws IOException{
		long originPos = file.getFilePointer();
		file.seek(0);
		long position = file.readLong();
		file.seek(originPos);
		return position;
	}
}
